package controllers

import (
	"alarmservice/com"
	"alarmservice/model"
	"alarmservice/service"
	"alarmservice/tracingservice"
	"math"
	"strconv"
	"time"

	"github.com/astaxie/beego"
)

type ApiController struct {
	baseController
	Project *model.Project
}

func (c *ApiController) NextPrepare() {
	//检查请求是否合法
	c.checkReq()
}

//检查请求是否合理
func (c *ApiController) checkReq() {
	//必须携带 t 参数，为当前实现戳。请求必须为GET
	//参数通过按 k进行排序，顺序排序，keyvaluekeyvalue的方式连接并最后连接securekey
	//做md5算法，作为参数s发送

	getParams, ok := c.Data["GET"].(map[string]string)
	if !ok {
		c.returnJson(com.ApiUnknowFailed("get params error"))
		return
	}

	s, sOk := getParams["s"]
	t, tOk := getParams["t"]
	k, kOk := getParams["k"]
	if !sOk || !tOk || !kOk {
		c.returnJson(com.ApiUnknowFailed("need 's' or 't' or 'k' params"))
		return
	}

	delete(getParams, "s")

	//检查project是否存在

	project := &model.Project{Apikey: k}

	err := model.GetByExample(project)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed("not found project"))
		return
	}

	localS, err := com.SignParams(getParams, project.Securekey)

	if err != nil || localS != s {
		c.returnJson(com.ApiReturn(com.ApiErrSignError, com.ApiErrMsgSign, ""))
		return
	}

	//检查时间是否合法

	reqTimeStamp, _ := strconv.ParseInt(t, 10, 64)
	reqTime := time.Unix(reqTimeStamp, 0)

	timeDelta := time.Now().Sub(reqTime)
	if int(math.Abs(timeDelta.Seconds())) > 3600 {
		c.returnJson(com.ApiUnknowFailed("time expired"))
		return
	}

	c.Project = project
}

//触发一个Tracing tkey
func (c *ApiController) Trigger() {
	getParams := c.Data["GET"].(map[string]string)
	tkey, ok := getParams["tkey"]
	if !ok {
		c.returnJson(com.ApiUnknowFailed("need tkey params"))
		return
	}

	data := getParams["data"]

	tracing := &model.Tracing{Key: tkey, ProjectId: c.Project.Id}

	err := model.GetByExample(tracing)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed("get tracing err!"))
		return
	}

	itracing, _ := tracingservice.NewITracing(tracing)
	//触发触发动作
	err = itracing.Trigger(data)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed(err.Error()))
		return
	}
	c.returnJson(com.ApiSucc(""))
}

func pushWarningMsg(project *model.Project, tracing *model.Tracing, warningData string) bool {
	//获取跟随用户

	followProjects := make(model.SliceFollowProject, 0)

	err := model.Orm.Where("project_id=?", project.Id).Find(&followProjects)

	if err != nil {
		return false
	}

	mobileLogins, err := model.GetMobileLoginFromUserIdContainer(followProjects)
	if err != nil {
		return false
	}

	if len(mobileLogins) == 0 {
		return false
	}

	androidUids := make([]int64, 0)
	iosUids := make([]int64, 0)

	//解析不同系统，准备发送消息
	for _, v := range mobileLogins {
		switch v.Os {
		case "android":
			androidUids = append(androidUids, v.Uid)
		case "ios":
			iosUids = append(iosUids, v.Uid)
		}
	}

	msgContent := project.Title + ":\"" + tracing.Key + "\"发生报警!"

	if len(androidUids) > 0 {
		//发送android信息
		msg, err := service.FastGetAndroidMessage("IOT报警", msgContent)
		if err != nil {
			beego.Error(err)
			return false
		}
		err = service.PushAndroidMessageByUids(msg, androidUids)
		if err != nil {
			beego.Error(err)
			return false
		}
	}

	if len(iosUids) > 0 {
		msg, err := service.FastGetIosMessage(msgContent)
		if err != nil {
			beego.Error(err)
			return false
		}
		err = service.PushIOSMessageByUids(msg, iosUids, beego.AppConfig.String("runmode"))

		if err != nil {
			beego.Error(err)
			return false
		}
	}

	return true
}
